package com.itjeffrey.autocode.security;

import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.itjeffrey.autocode.common.Result;
import com.itjeffrey.autocode.util.WebUtil;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 自定义 Security 访问拒绝处理器
 */
@Component
public class SecureAccessDeniedHandler implements AccessDeniedHandler {

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                       AccessDeniedException e) throws IOException, ServletException {
        if (WebUtil.isAjax(httpServletRequest)) {
            Result result = Result.fail(403, "无权访问！");
            WebUtil.write(JSON.toJSONString(result));
        } else {
            httpServletResponse.sendRedirect("/error/403");
        }
    }
}
